package admin

import (
	"context"
	"encoding/json"
	"fmt"
	"math/rand"
	"time"

	"gitee.com/gopher2011/xzs/internal/svc"
	"gitee.com/gopher2011/xzs/internal/types"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"github.com/tal-tech/go-zero/core/logx"
)

type SendSmsCodeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSendSmsCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) SendSmsCodeLogic {
	return SendSmsCodeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SendSmsCodeLogic) SendSmsCode(req types.PhoneReq) (*types.RestResponse, error) {
	//随机生成一个验证码
	code := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
	//调用阿里云短信接口发送短信
	client, err := dysmsapi.NewClientWithAccessKey(l.svcCtx.Config.Sms.RegionId, l.svcCtx.Config.Sms.AppKey, l.svcCtx.Config.Sms.AppSecret)
	if err != nil {
		return nil, err
	}
	request := dysmsapi.CreateSendSmsRequest()
	//request属性设置
	request.Scheme = "https"
	request.SignName = l.svcCtx.Config.Sms.SignName
	request.TemplateCode = l.svcCtx.Config.Sms.TemplateCode
	request.PhoneNumbers = req.Phone

	//使用json字符串发送验证码
	par, err := json.Marshal(map[string]interface{}{
		"code": code,
	})
	//设置验证码
	request.TemplateParam = string(par)
	response, err := client.SendSms(request)

	//测试
	fmt.Println(response)

	//检查返回结果，并判断发生状态
	if response.Code != "OK" {
		//插入数据库操作
	}

	return &types.RestResponse{}, nil
}
